package com.zl.auth.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zl.auth.client.utils.HttpClientUtil;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    public static final Map<String,String> token_freshtoken_map = new HashMap();//todo 将token信息存库，查询
    @PostMapping("client/login")
    public String login(){
        return "";
    }
    @PostMapping("client/getUserInfo")
    public String getUserinfo(HttpServletRequest request){
        String userinfo = (String) request.getSession().getAttribute("userinfo");
        return userinfo;
    }
    @PostMapping("client/refresh_token")
    public String refresh_token(HttpServletRequest request, HttpServletResponse response){
        String userinfo = (String) request.getSession().getAttribute("userinfo");
        if (userinfo != null){
            String refreshtoken = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0){
                for (int i = 0; i < cookies.length; i++) {
                    Cookie c = cookies[i];
                    if ("access_token".equals(c.getName())){
                        String token = c.getValue();
                        refreshtoken = token_freshtoken_map.get(userinfo);//todo 需要改username
                    }
                }
            }
            Map<String,Object> params = new HashMap();
            params.put("grant_type","refresh_token");
            params.put("refresh_token",refreshtoken);
            Header h = new BasicHeader("Authorization", "Basic "+ Base64Utils.encodeToString("free-web:123456".getBytes()));
            String s = HttpClientUtil.sendPostForm("http://localhost:18092/oauth/token", params, new ArrayList<Header>() {{
                this.add(h);
            }}, null);
            JSONObject jsonObject = JSON.parseObject(s);
            if (jsonObject.get("access_token") != null){
                String access_token = jsonObject.getString("access_token");
                Cookie cookie = new Cookie("access_token",access_token);
                cookie.setHttpOnly(false);
                cookie.setMaxAge(7200);
                cookie.setPath("/");
                cookie.setDomain("localhost");
                response.addCookie(cookie);
                refreshtoken = jsonObject.getString("refresh_token");
                token_freshtoken_map.put(userinfo,refreshtoken);//todo 退出时清除
            }
        }
        return null;
    }
}
